<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input placeholder="搜索内容" style="width: 200px;" size="mini" class="filter-item" />
      <el-button class="filter-item" type="success" size="mini" icon="el-icon-search">搜索</el-button>
    </div>
    <div class="filter-container" style="display: flex;justify-content: space-between;">
      <el-button-group>
        <el-button v-permission="['admin','menu:add']" class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="formAdd()">新增</el-button>
        <el-button v-permission="['admin','menu:edit']" class="filter-item" disabled size="mini" type="success" icon="el-icon-edit" @click="formEdit()">修改</el-button>
        <el-button v-permission="['admin','menu:delete']" class="filter-item" disabled size="mini" type="danger" icon="el-icon-delete">删除</el-button>
        <el-button class="filter-item" disabled size="mini" type="warning" icon="el-icon-download">导出</el-button>
      </el-button-group>
      <el-button-group>
        <el-button class="filter-item" size="mini" icon="el-icon-refresh" @click="refresh()" />
      </el-button-group>
    </div>
    <!--表单渲染-->
    <el-dialog :visible.sync="formVisible" append-to-body :close-on-click-modal="false" :title="formType.title" width="600px">
      <el-form ref="form" :rules="rules" :inline="true" :model="form" size="small" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="role_name">
              <el-input v-model="form.role_name" placeholder="组件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识" prop="auth_name">
              <el-input v-model="form.auth_name" placeholder="角色权限，如 admin ，superadmin" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色级别" prop="level">
          <el-input-number v-model.number="form.level" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" :rows="4" type="textarea" style="width: 464px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submit()">确认</el-button>
      </div>
    </el-dialog>

    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            v-loading="loading"
            :data="listData"
            style="width: 100%"
            row-key="id"
            highlight-current-row
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="tabSelectionChange"
            @current-change="handleCurrentChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="role_name" label="角色名称" width="120" />
            <el-table-column prop="auth_name" label="权限标识" width="120" />
            <el-table-column prop="level" label="角色级别" />
            <el-table-column prop="remark" :show-overflow-tooltip="true" label="描述" />
            <el-table-column prop="create_time" :show-overflow-tooltip="true" label="创建时间" width="135">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.create_time) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-permission="['admin','menu:delete','menu:edit']" label="操作" class-name="small-padding fixed-width" width="120" align="center" fixed="right">
              <template slot-scope="{row,$index}">
                <el-button v-permission="['admin','menu:edit']" type="primary" size="mini" icon="el-icon-edit" style="width: auto;" @click="formEdit(row)" />
                <el-button v-permission="['admin','menu:delete']" size="mini" type="danger" icon="el-icon-delete" style="width: auto;" @click="handleDelete(row,$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['admin','menu:add','menu:delete','menu:edit']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            check-strictly
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { parseTime } from '@/utils/index'
// 权限判断函数
import checkPermission from '@/utils/permission'
import crudRole from '@/api/system/role'
import crudMenu from '@/api/system/menu'
const defaultForm = { id: null, role_name: null, auth_name: null, renark: null, create_time: null, level: 5 }
export default {
  name: 'Role',
  components: { },
  data() {
    return {
      checkPermission,
      // 表数据
      listData: [],
      // 加载状态
      loading: false,
      // 提交数据加载状态
      submitLoading: false,
      // 显示表单
      formVisible: false,
      // 类型说明
      titleStatus: { add: '新增', edit: '编辑信息' },
      // 表单类型
      formType: { value: '', title: '' },
      // 表单字段初始数据
      form: defaultForm,
      // 数据校验
      rules: {
        role_name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        auth_name: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ]
      },
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      defaultProps: { children: 'children', label: 'label' },
      level: 3
    }
  },
  created() {
    // 页面加载时判断 api 权限，有权限再请求
    if (checkPermission(['admin', 'role:list'])) {
      this.getList()
    }
    if (checkPermission(['admin', 'menu:tree'])) {
      this.getMenuTree()
    }
    if (checkPermission(['admin', 'role:level'])) {
      crudRole.getLevel().then(res => {
        if (res.code === 0) {
          this.level = res.data
        }
      })
    }
  },
  methods: {
    parseTime,
    // 初始化表单
    formInit(formName, type, data) {
      if (type !== 'add' && type !== 'edit') {
        return false
      }
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      // 字段值初始化
      this.formType = {
        value: type,
        title: this.titleStatus[type]
      }
      this.form = JSON.parse(JSON.stringify(data))
      // 显示表单
      this.formVisible = true
      return true
    },
    // 获取数据列表
    getList() {
      var that = this
      this.loading = true
      crudRole.getAll().then(res => {
        that.listData = res.data
        this.loading = false
      }).catch(res => {
        this.loading = false
      })
    },
    // 刷新表单
    refresh() {
      this.getList()
      this.getMenuTree()
      crudRole.getLevel().then(res => {
        if (res.code === 0) {
          this.level = res.data
        }
      })
    },
    // 表单新增
    formAdd() {
      this.formInit('form', 'add', defaultForm)
    },
    // 表单编辑
    formEdit(data) {
      if (data) {
        this.formInit('form', 'edit', data)
      }
    },
    // 删除处理
    handleDelete(row, $index) {
      crudRole.del({ id: row.id }).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '操作完成！',
            type: 'success'
          })
        }
        this.getList()
      })
    },
    /**
     * 提交新增/编辑
     */
    submit() {
      this.$refs['form'].validate((valid) => {
        this.submitLoading = true
        if (valid) {
          if (this.formType.value === 'edit') {
            crudRole.edit(this.form).then(res => {
              this.$notify({
                title: '更新信息成功！',
                type: 'success'
              })
              this.getList()
              this.submitLoading = false
              this.formVisible = false
            }).catch(res => {
              this.submitLoading = false
            })
          } else if (this.formType.value === 'add') {
            crudRole.add(this.form).then(res => {
              this.$notify({
                title: '新增成功！',
                type: 'success'
              })
              this.getList()
              this.submitLoading = false
              this.formVisible = false
            }).catch(res => {
              this.submitLoading = false
            })
          }
        } else {
          this.$message({
            message: '数据校验失败',
            type: 'warning'
          })
          this.submitLoading = false
          return false
        }
      })
    },
    // 选中数据行处理
    tabSelectionChange(res) {
      console.log(res)
    },
    handleCurrentChange(val) {
      console.log(this.level)
      console.log(val, this.level <= val.level)
      if (val) {
        const that = this
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        this.showButton = this.level <= val.level
        // 初始化
        this.menuIds = []
        // 菜单数据需要特殊处理
        val.menus.forEach(function(data, index) {
          that.menuIds.push(data.id)
        })
      }
    },
    getMenuTree() {
      crudMenu.tree().then(res => {
        if (res.code === 0) {
          this.menus = res.data
        }
      })
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, menus: [] }
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getHalfCheckedNodes().forEach(function(data, index) {
        role.menus.push(data.id)
      })
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach(function(data, index) {
        role.menus.push(data)
      })
      crudRole.editMenu(role).then(res => {
        this.$notify({
          title: '操作完成！',
          type: 'success'
        })
        this.menuLoading = false
        this.getList()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response.data.message)
      })
    }
  }
}
</script>
